<template>
  <div class="profiler-container">
    <!-- 左侧 1D Profiler -->
    <div class="profiler-1d">
      <h5>1D Profiler</h5>
      <div class="upload-section">
        <el-upload
          class="upload-demo"
          :action="`${config.baseURL}/profile/upload`"
          :on-success="handleUpload1DSuccess"
          :on-error="handleUpload1DError"
          :multiple="true"
          :limit="8"
          :show-file-list="false"
          accept=".xlsx,.xls">
          <el-button type="primary">上传Excel文件</el-button>
        </el-upload>
      </div>

      <!-- 文件列表区域 -->
      <div class="files-section">
        <div v-for="(file, index) in uploadedFiles" :key="file.id" class="file-item">
          <el-checkbox v-model="file.selected" @change="handleCheckboxChange">
            {{ file.name }}
          </el-checkbox>
        </div>
      </div>

      <!-- 1D图表区域 -->
      <div class="chart-section" v-if="uploadedFiles.length > 0">
        <div ref="chart1DRef" style="width: 100%; height: 600px"></div>
      </div>
    </div>

    <!-- 右侧 2D Profiler -->
    <div class="profiler-2d">
      <h5>2D Profiler</h5>
      <el-upload
        :key="uploadKey"
        class="upload-demo"
        action=""
        :auto-upload="false"
        :on-change="handleFileChange2D"
        :show-file-list="false"
        :accept="'.csv'"
        :disabled="isLoading"
        :limit="1"
        :before-upload="beforeUpload2D"
      >
        <el-button type="primary" :loading="isLoading">
          {{ isLoading ? '处理中...' : '选择CSV文件' }}
        </el-button>
        <template #tip>
          <div class="el-upload__tip">
            请上传CSV格式文件 {{ currentFileName ? `(当前文件: ${currentFileName})` : '' }}
          </div>
        </template>
      </el-upload>

      <div class="chart-container">
        <div class="heatmap" ref="heatmapRef">
          <div class="coordinate-lines">
            <div class="vertical-line"></div>
            <div class="horizontal-line"></div>
          </div>
          <div class="y-axis">
          </div>
          <div class="heatmap-center">
            <div v-for="(row, i) in processedData" :key="i" class="heatmap-row">
              <div v-for="(value, j) in row" :key="j" class="heatmap-cell" 
                :style="{ backgroundColor: getColor(value) }" 
                :title="`值: ${value}`">
              </div>
            </div>
          </div>
          <div class="x-axis">
          </div>
        </div>
        
        <div class="color-scale">
          <div class="scale-gradient"></div>
          <div class="scale-labels">
            <span>0</span>
            <span>5</span>
            <span>9</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import axios from '../../plugins/axios'
import { config } from '../../config'
import { ElMessage } from 'element-plus'

// 1D Profiler 相关
const chart1DRef = ref(null)
let chart1D = null
const uploadedFiles = ref([])

// 1D图表颜色数组
const colors1D = [
  '#5470c6', '#91cc75', '#fac858', '#ee6666',
  '#73c0de', '#3ba272', '#fc8452', '#9a60b4'
]

// 2D Profiler 相关
const heatmapRef = ref(null)
const rawData = ref(null)
const isLoading = ref(false)
const uploadKey = ref(0)
const currentFileName = ref('')

// 1D Profiler 方法
const initChart1D = async () => {
  await nextTick()
  if (!chart1DRef.value) return

  if (chart1D) {
    chart1D.dispose()
  }
  chart1D = echarts.init(chart1DRef.value)
}

const updateChart1D = () => {
  if (!chart1D || uploadedFiles.value.length === 0) return

  const selectedFiles = uploadedFiles.value.filter(file => file.selected)

  if (selectedFiles.length === 0) {
    chart1D.clear()
    return
  }

  const series = [
    {
      name: 'Boundary Line 1',
      type: 'line',
      markLine: {
        symbol: ['none', 'none'],
        silent: true,
        data: [{ xAxis: 150 }],
        lineStyle: {
          color: '#ff0000',
          type: 'dashed',
          width: 1
        }
      }
    },
    {
      name: 'Boundary Line 2',
      type: 'line',
      markLine: {
        symbol: ['none', 'none'],
        silent: true,
        data: [{ xAxis: -150 }],
        lineStyle: {
          color: '#ff0000',
          type: 'dashed',
          width: 1
        }
      }
    },
    ...selectedFiles.map((file, index) => ({
      name: file.name,
      type: 'line',
      smooth: true,
      symbol: 'none',
      data: file.data.map(item => [item.p, item.v]),
      lineStyle: {
        color: colors1D[index % colors1D.length]
      }
    }))
  ]

  const option = {
    title: {
      text: 'Vertical Profile Data'
    },
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      min: -180,
      max: 180,
      interval: 20,
      axisLabel: {
        formatter: '{value}mm'
      },
      scale: false
    },
    yAxis: {
      type: 'value',
      min: 0.2,
      max: 1.2,
      interval: 0.2
    },
    series: series
  }

  chart1D.setOption(option, true)
}

// 2D Profiler 方法
const processedData = computed(() => {
  if (!rawData.value || !rawData.value.length) return []
  
  const totalRows = rawData.value.length
  
  if (totalRows < 30) {
    ElMessage.warning('数据行数不足，无法处理')
    return []
  }

  return rawData.value.map(row => {
    const leftPadding = Array(6).fill(0)
    const rightPadding = Array(6).fill(0)
    return [...leftPadding, ...row, ...rightPadding]
  })
})

const getColor = (value) => {
  if (value === undefined || value === null) return '#FFFFFF'
  
  const colors = [
    '#FFF5F0', '#FEE0D2', '#FCBBA1', '#FC9272',
    '#FA6A4A', '#EF3B2C', '#CB181D', '#A50F15',
    '#67000D'
  ]
  
  const index = Math.min(Math.floor(value), colors.length - 1)
  return colors[index]
}

// 事件处理方法
const handleUpload1DSuccess = (response, file) => {
  const formattedData = response.data.map(item => ({
    p: Number(item.mm),
    v: Number(item.ma)
  }))

  uploadedFiles.value.push({
    id: Date.now(),
    name: file.name,
    selected: true,
    data: formattedData
  })
}

const handleUpload1DError = (error) => {
  console.error('Upload failed:', error)
  ElMessage.error('文件上传失败')
}

const handleCheckboxChange = () => {
  updateChart1D()
}

const beforeUpload2D = (file) => {
  const isCSV = file.name.endsWith('.csv')
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isCSV) {
    ElMessage.error('只能上传 CSV 文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }
  return true
}

const handleFileChange2D = async (file) => {
  if (!file) {
    ElMessage.warning('请选择文件')
    return
  }

  isLoading.value = true
  try {
    const formData = new FormData()
    formData.append('file', file.raw)
    
    const response = await axios.post(
      `/angleProfile/upload`,
      formData,
      {
        headers: { 'Content-Type': 'multipart/form-data' },
        timeout: 30000
      }
    )
    
    if (response.data && Array.isArray(response.data)) {
      if (response.data.length < 30) {
        throw new Error('数据行数不足，需要至少30行数据')
      }
      
      rawData.value = response.data
      currentFileName.value = file.name
      ElMessage.success(`文件 ${file.name} 处理成功，已在数据两侧各添加6列0值`)
    } else {
      throw new Error('返回的数据格式不正确')
    }
  } catch (error) {
    console.error('文件处理失败:', error)
    ElMessage.error(
      error.response?.data?.message || 
      error.message || 
      '文件处理失败，请重试'
    )
    rawData.value = null
    currentFileName.value = ''
  } finally {
    isLoading.value = false
    uploadKey.value++
  }
}

// 生命周期钩子
onMounted(async () => {
  await initChart1D()
  updateChart1D()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (chart1D) {
    chart1D.dispose()
    chart1D = null
  }
})

// 监听器
watch(() => uploadedFiles.value, async () => {
  await initChart1D()
  updateChart1D()
}, { deep: true })

const handleResize = () => {
  if (chart1D) {
    chart1D.resize()
  }
}
</script>

<style scoped>
.profiler-container {
  display: flex;
  width: 100%;
  height: 100vh;
  padding: 20px;
  gap: 20px;
}

.profiler-1d, .profiler-2d {
  flex: 1;
  height: 100%;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow-y: auto;
}

/* 1D Profiler 样式 */
.upload-section {
  margin-bottom: 20px;
}

.files-section {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.file-item {
  margin: 0;
  flex: 0 0 auto;
}

/* 2D Profiler 样式 */
.chart-container {
  position: relative;
  width: 100%;
  aspect-ratio: 3/2;
  background-color: #FFFFFF;
  border: 1px solid #ddd;
  margin: 2vh auto;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: visible;
}

.heatmap {
  position: relative;
  width: 90%;
  height: 90%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0;
  line-height: 0;
}

.coordinate-lines {
  position: absolute;
  width: 90%;
  height: 90%;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 3;
  pointer-events: none;
}

.vertical-line {
  position: absolute;
  left: 50%;
  height: 100%;
  width: 1px;
  background-color: #000;
  transform: translateX(-50%);
}

.horizontal-line {
  position: absolute;
  top: 50%;
  width: 100%;
  height: 1px;
  background-color: #000;
  transform: translateY(-50%);
}

.heatmap-center {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%) scale(3);
  display: block;
  font-size: 0;
  line-height: 0;
  letter-spacing: -1px;
  word-spacing: -1px;
  white-space: nowrap;
  z-index: 2;
  transform-origin: center center;
}

.heatmap-row {
  display: block;
  height: 2.5px;
  margin: 0;
  padding: 0;
  font-size: 0;
  line-height: 0;
  white-space: nowrap;
}

.heatmap-cell {
  width: 8.8px;
  height: 2.5px;
  display: inline-block;
  margin: 0 !important;
  padding: 0 !important;
  border: 0 !important;
  vertical-align: top;
  font-size: 0;
  line-height: 0;
}

.color-scale {
  position: absolute;
  top: 0;
  right: 0;
  width: 20%;
  min-width: 100px;
  transform: translate(0, -120%);
}

.scale-gradient {
  width: 100%;
  height: 20px;
  background: linear-gradient(to right, 
    #FFF5F0, #FEE0D2, #FCBBA1, #FC9272,
    #FA6A4A, #EF3B2C, #CB181D, #A50F15,
    #67000D
  );
  border-radius: 4px;
  margin: 4px 0;
}

.scale-labels {
  display: flex;
  justify-content: space-between;
  width: 100%;
  font-size: clamp(10px, 1vw, 14px);
  font-weight: bold;
}

h5 {
  margin-bottom: 20px;
  font-size: 18px;
  color: #333;
}
</style>